package dk.iha;

import android.os.Handler;
import android.os.Message;

/**
 * Wraps the sensor and handles timers 
 * @author NK
 *
 */
public class SensorHandler {
	private long TimeOut=0;
	private ISensor sensor = null;
	private boolean hasData=false;
	private Handler handler=null;
	private long runEveryInterval = 0;
	private long intervalCtr=0;
	private Handler onSensorFinishedHandler=null;
	/**
	 * Constructor
	 * @param sensorMain
	 */
	public SensorHandler(ISensor sensor, Handler onSensorFinishedHandler, long timeOutValue, long runEveryInterval){
		this.TimeOut = timeOutValue;
		this.sensor = sensor;
		this.runEveryInterval = runEveryInterval;
		this.onSensorFinishedHandler = onSensorFinishedHandler;
	}
	
	/**
	 * returns the sensor wrapped by this SensorHandler
	 * @return
	 */
	public ISensor getSensor(){
		return sensor;
	}
	
	/**
	 * Resets the hasData flag
	 */
	public void reset(){
		//clears the hasData flags after data has been used
		hasData=false;
	}
	
	/**
	 * Called on timer elapsed
	 */
	public Runnable runnable = new Runnable() {
		public void run() {
			//Stop the generic sensor
			sensor.stop();
			hasData=true;
			//call back to sensormain on complete
			onSensorFinishedHandler.dispatchMessage(new Message());
		}
	};
	
	public boolean isRunning(){
		return sensor.isRunning();
	}
	
	public boolean hasData() {
		return hasData;
	}
	
	public void stop(){
		if(sensor.isRunning()){
			sensor.stop();
			hasData=true;
		}		

		if(handler != null){
			handler.removeCallbacks(runnable);
			handler = null;
		}
	}
	
	/**
	 * starts the sensor datacollection and initialises the timer
	 */
	public void start(){
		//only run every "runEveryInterval" time start is called
		// run the first time
		if(intervalCtr++ % runEveryInterval != 0)
			return;

		//start the sensor datacollection
		sensor.start();
		//setup timer for the datacollection
		handler = new Handler();
		handler.postDelayed(runnable, TimeOut);
	}
}
